package net.takela.common.webflux.security.handler;


import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SysFuncLoadService {
//    @Autowired
//    private AclService aclService;
    public LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> getRequestConfigMap() {

//        List<SysFunction> sysFunctions = aclService.getAllFunctions();
//
//        if (CollectionUtils.isEmpty(sysFunctions)) {
//            return new LinkedHashMap<>();
//        }
//
        Map<String, Set<String>> urlPermissionMap = new HashMap<>();
//
//        for (SysFunction func : sysFunctions) {
//            List<String> urls = new ArrayList<>();
//            if (!StringUtils.isEmpty(func.getRoute())){
//                String url = determineAntUrl(func.getRoute());
//                urls.add(url);
//            }
//            if (!org.springframework.util.CollectionUtils.isEmpty(func.getDependRoutes())){
//                func.getDependRoutes().stream().forEach(url->urls.add(determineAntUrl(url)));
//            }
//            for (String url: urls){
//                Set<String> configAttributes = urlPermissionMap.get(url);
//                if (configAttributes == null) {
//                    configAttributes = new HashSet<>();
//                }
//                configAttributes.add(String.valueOf(func.getId()));
//                urlPermissionMap.put(url, configAttributes);
//            }
//        }

        Set<String> funcIds = new HashSet<>();
        funcIds.add("0");
        urlPermissionMap.put(determineAntUrl("/"),  funcIds) ;
        LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<>();

        for(String url : urlPermissionMap.keySet()) {
            Set<String> permissions = urlPermissionMap.get(url);
            Collection<ConfigAttribute> configAttributes = permissions.stream().map(permission -> new SecurityConfig(permission)).collect(Collectors.toSet());

            requestMap.put(new AntPathRequestMatcher(url), configAttributes);
        }
        return requestMap;
    }

    /**
     * 去掉最后一个 <code>/</code> 后的内容，以 <code>**</code> 代替，以匹配 <code>ant</code> 风格。
     * @param url 功能地址
     * @return ant风格地址
     */
    private String determineAntUrl(String url) {
        if (StringUtils.isEmpty(url)) {
            return null;
        }
        if (url.endsWith("/")){
            return url.substring(0, url.lastIndexOf("/")) + "/**";
        }
        return url;
    }

}
